let express = require('express');
let path = require('path');
const fs = require('fs');
let app = express()
let url = path.join(__dirname + '/src')
app.use(express.static(url))

//配置跨域中间件
const cors = require('cors')
app.use(cors())


let user = require('./api/user')
let comment_dishes = require('./api/comment_dishes')
let menu = require('./api/menu')
let cart = require('./api/cart')
let category = require('./api/category')
let order = require('./api/order')

app.use(express.json(),express.urlencoded())

app.use((req,res,next)=>{
    console.log(req.path.indexOf('/api') == -1);
        if(req.path.indexOf('/api') == -1){
            fs.readFile(path.join(__dirname,'src/index.html'),(err,content)=>{
                res.set({'Content-Type':'text/html;charset=utf-8'})
                res.send(content)
            })
        }else{
          next()
        }
})

const jwt = require('./api/auth');// 引入jwt token工具
app.use(function (req, res, next) {
  // 这里知识把登陆和注册请求去掉了，其他的多有请求都需要进行token校验 
  if(jwt.ignoreAuth.includes(req.path)){ 
    console.log('发信ip地址',req.ip,'请求路径',req.path);  
    next();
  } else {
    console.log('请求路径',req.path)
    console.log('发信ip地址:',req.ip);
    //获取请求头携带的token
    let token = req.headers.authorization;
    //验证token是否过期
    let result = jwt.verifyToken(token);
    // 如果验证通过就next，否则就返回登陆信息不正确(code == 100就是异常情况)
    if (result.code == 100) {
      res.send({
        code: 401,
        msg: 'token验证失败'
      });
    } else {
      next();
    }
  }
});


//用户
app.use('/api/user',user)
//评论
app.use('/api',comment_dishes)
//菜单
app.use('/api/menu',menu)
//分类
app.use('/api',category)
//购物车
app.use('/api/cart',cart)
//订单
app.use('/api/order',order)

app.listen(2203,()=>{
    console.log('server running at port 2203');
})